
package com.sdonkey.score.controller;


import com.alibaba.fastjson.JSONObject;
import com.sdonkey.score.bean.AdvertiserLoginBean;
import com.sdonkey.score.bean.LoginReturnBean;
import com.sdonkey.score.constants.RedisKey;
import com.sdonkey.score.service.ILoginService;
import com.sdonkey.score.util.CookieUtil;
import com.sdonkey.score.util.JacksonMapper;
import com.sdonkey.score.util.MD5;
import com.sdonkey.score.util.StringUtil;
import com.sdonkey.score.vo.ResultErrorVo;
import com.sdonkey.score.vo.ResultSuccessVo;
import com.sdonkey.score.vo.ResultVo;
import com.sdonkey.score.vo.SystemInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @title  广告主 登录
 * @author MengXue
 * @email aoxiang66@sina.cn
 * @time 2016/11
 * @version 1.0
 */
@Controller
@RequestMapping(method = RequestMethod.POST)
public class LoginAction {

	@Autowired
	private ILoginService loginService;
	@Autowired
	private JedisPool jedisPool;

	private static Logger logger=Logger.getLogger(LoginAction.class);

	/**
	 * 登录(加密)
	 *
	 * @param req
	 * @param res
	 * @param session
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/dologin",method = RequestMethod.POST)
	@ResponseBody
	public ResultVo dologin(HttpServletRequest req, HttpServletResponse res, HttpSession session, Map<String, Object> model) throws Exception {


		
		//把memberName  password  rememberMe存到session中
		String memberName = ServletRequestUtils.getStringParameter(req, "memberName", "");
		session.setAttribute("memberName", memberName);
		System.out.println(memberName);

		String password = ServletRequestUtils.getStringParameter(req, "password", "");

		String rememberMe = ServletRequestUtils.getStringParameter(req, "rememberMe", "");
		@SuppressWarnings("unused")
		String flag = ServletRequestUtils.getStringParameter(req, "flag", "");
		String memberName_hidden = ServletRequestUtils.getStringParameter(req, "memberName_hidden", "");
		session.setAttribute("memberName_hidden", memberName_hidden);

		//判断 memberName， password 不为空
		if (StringUtils.isEmpty(memberName) || StringUtils.isEmpty(password)) {
			return new ResultErrorVo("用户名或密码不能为空");
		}
		LoginReturnBean loginReturnBean = loginService.login(memberName);
		if (loginReturnBean == null ) {
			logger.info("用户名不存在");
			return new ResultErrorVo("用户名不存在");
		}
		if("1".equals(loginReturnBean.getStatus())){
			return new ResultErrorVo("用户处于冻结状态，暂无法登录");
		}
		//获取密码 解密
		String dbPassword = loginReturnBean.getPassword();
		if(!password.equals(dbPassword)){
//			session.setAttribute("password", password);
			// MD5加密
			String dbInputPassword = MD5.encode(password);
			// 是否与库中的密码一致
			if (!dbInputPassword.equals(dbPassword)) {
				ResultVo resultVo = new ResultErrorVo("incorrect_password");
				String error_json = JacksonMapper.objectToJsonString(resultVo);
				model.put("message", error_json);
				return new ResultErrorVo("用户名或密码不正确");
			}
		}


		// 广告主用户登录
		AdvertiserLoginBean advertiserLogin1 = new AdvertiserLoginBean(memberName, ServletRequestUtils.getStringParameter(req, "password", ""));
		Cookie cookie = null;
		try {
			logger.info("登录成功记录redis 已经session、cookie");
			Jedis jedis = jedisPool.getResource();
//			jedis.set(RedisKey.user_login_key + memberName, memberName);
			jedis.set(RedisKey.user_login_id + loginReturnBean.getAdvId(), JSONObject.toJSONString(loginReturnBean));
			jedis.expire(RedisKey.user_login_id + loginReturnBean.getAdvId(), 30*60);

			if (rememberMe != null && "true".equals(rememberMe)) {
                //用户名密码cookie
                String passwordMd5 =null;
                if(!password.equals(dbPassword)){
                    passwordMd5 = MD5.encode(password);
                }else{
                    passwordMd5 = password;
                }
                jedis.set("password" + memberName, passwordMd5);
            }else{
                jedis.del("password" + memberName);
            }
			//获取站内信条数
//			int unreadCount = msgService.getUnreadNum(loginReturnBean.getDonkeyNum(),"广告主");
			loginReturnBean.setUnreadCount(0);
			logger.info("cookie advid "+loginReturnBean.getAdvId());
//			session.setAttribute("advId", loginReturnBean.getAdvId());
//			session.setAttribute("donkeynum", loginReturnBean.getDonkeyNum());
			cookie = new Cookie("advId",loginReturnBean.getAdvId());
//			cookie.setPath("/");
			cookie.setMaxAge(30*60);
			res.addCookie(cookie);
		} catch (Exception e) {
			logger.error("用户登录异常",e);
			e.printStackTrace();
		}
		//记录用户donkey_num,登录时间
		loginService.saveLoginLog(loginReturnBean.getDonkeyNum(), new Date());
		return new ResultSuccessVo(advertiserLogin1);

	}

	/**
	 * 退出登录清除session
	 *
	 * @throws Exception
	 */
	@RequestMapping(value = "/loginOut")
	@ResponseBody
	public ResultVo loginOut(HttpServletRequest req, HttpServletResponse rep) throws Exception {
		String cookieId = CookieUtil.getCookie(req, "advId");
		if(StringUtil.isBlank(cookieId)){
			return new ResultSuccessVo("用户session清空成功");
		}
		Jedis jedis = jedisPool.getResource();
		jedis.del(RedisKey.user_login_key+cookieId);
		return new ResultSuccessVo("用户session清空成功");
	}
	/**
	 * 退出后回退判断
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/backSpace", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo backSpace(HttpSession session) throws Exception {
		//清空session
		String donkeynum=(String) session.getAttribute("donkeynum");
		if(donkeynum==null){
			return new ResultErrorVo("用户退出登录，回退时跳转登录页面");
		}
		return new ResultSuccessVo("session值未被清除，不跳转");
	}


	@RequestMapping(value = "getUser")
	@ResponseBody
	public JSONObject getUser(HttpServletRequest request, HttpServletResponse response, HttpSession session){
		Jedis jedis = jedisPool.getResource();
		JSONObject result = new JSONObject();
		String cookieId = CookieUtil.getCookie(request, "advId");
		if(StringUtil.isBlank(cookieId)){
			result.put("username", null);
		}else{
			result.put("donkeynum", 1);//已登录
			String value = jedis.get(RedisKey.user_login_id + cookieId);
			JSONObject object = JSONObject.parseObject(value);
			String memberName = object.getString("donkeyNum");
			result.put("password", jedis.get("password" + memberName) );
			result.put("usernmae", object.getString("donkeyNum"));
		}
		return result;

	}

	/**
	 * 获取系统运行信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getSystemInfo", method = RequestMethod.GET)
	@ResponseBody
	public String getSystemInfo(HttpServletRequest request, String callback) {
		SystemInfo systemInfo = null;
		Map<String, Object> info = new HashMap<>();
		try {
			systemInfo = SystemInfo.getInstance(request);
			info.put("message", "1");
			info.put("data", systemInfo);
		} catch (Exception e) {
			info.put("message", "-1");
			info.put("error", e);
			e.printStackTrace();
		}
		String s = null;
		try {
			s = JacksonMapper.objectToJsonString(info);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return callback + "(" + s + ")";
	}






}
